package org.app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.app.common.Result;
import org.app.entity.Activity;
import org.app.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.app.exception.BusinessException;

@RestController
@RequestMapping("/activity")
public class ActivityController {
    
    private static final Logger log = LoggerFactory.getLogger(ActivityController.class);
    
    @Autowired
    private ActivityService activityService;
    
    /**
     * 分页查询活动列表
     */
    @GetMapping("/page")
    public Result<Page<Activity>> getActivityPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword) {
        Page<Activity> page = activityService.getActivityPage(pageNum, pageSize, status, keyword);
        return Result.success(page);
    }
    
    /**
     * 获取首页轮播图（前三个活动图片）
     */
    @GetMapping("/banner")
    public Result<List<Map<String, Object>>> getBannerImages() {
        List<Activity> activityList = activityService.getTopActivitiesForBanner(3);
        
        List<Map<String, Object>> bannerList = activityList.stream().map(activity -> {
            Map<String, Object> banner = new HashMap<>();
            banner.put("id", activity.getId());
            banner.put("title", activity.getTitle());
            banner.put("image", activity.getCover());
            return banner;
        }).collect(Collectors.toList());
        
        return Result.success(bannerList);
    }
    
    /**
     * 获取首页推荐活动（最新三个活动）
     */
    @GetMapping("/recommend")
    public Result<List<Activity>> getRecommendActivities() {
        List<Activity> recommendList = activityService.getRecentActivities(3);
        return Result.success(recommendList);
    }
    
    /**
     * 管理员分页查询活动列表
     */
    @GetMapping("/admin/page")
    public Result<Page<Activity>> getAdminActivityPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword) {
        Page<Activity> page = activityService.getAdminActivityPage(pageNum, pageSize, status, keyword);
        return Result.success(page);
    }
    
    /**
     * 根据ID查询活动详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(
            @PathVariable Long id,
            HttpServletRequest request) {
        Activity activity = activityService.getById(id);
        if (activity == null) {
            return Result.error("活动不存在");
        }
        
        // 判断当前用户是否已报名
        Long userId = (Long) request.getAttribute("userId");
        boolean isSignedUp = false;
        
        if (userId != null) {
            isSignedUp = activityService.isSignedUp(id, userId);
        }
        
        Map<String, Object> map = new HashMap<>();
        map.put("activity", activity);
        map.put("isSignedUp", isSignedUp);
        
        return Result.success(map);
    }
    
    /**
     * 添加活动（管理员）
     */
    @PostMapping
    public Result<Void> add(@Valid @RequestBody Activity activity, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        activity.setCreatorId(userId);
        activity.setCurrentParticipants(0);
        activityService.save(activity);
        return Result.success();
    }
    
    /**
     * 修改活动（管理员）
     */
    @PutMapping
    public Result<Void> update(@Valid @RequestBody Activity activity) {
        activityService.updateById(activity);
        return Result.success();
    }
    
    /**
     * 删除活动（管理员）
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        activityService.removeById(id);
        return Result.success();
    }
    
    /**
     * 更新活动状态（管理员）
     */
    @PutMapping("/status/{id}")
    public Result<Void> updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        activityService.updateStatus(id, status);
        return Result.success();
    }
    
    /**
     * 获取活动参与者列表
     */
    @GetMapping("/participants/{id}")
    public Result<List<Map<String, Object>>> getParticipants(@PathVariable Long id) {
        List<Map<String, Object>> participants = activityService.getActivityParticipants(id);
        return Result.success(participants);
    }
    
    /**
     * 用户报名活动
     */
    @PostMapping("/signup/{id}")
    public Result signup(
            @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        try {
            if(activityService.signup(id, userId)){
                return Result.success("预约成功");
            }
            return Result.error("预约失败");
        } catch (BusinessException e) {
            // 捕获业务异常并返回友好提示
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("活动预约异常", e);
            return Result.error("系统异常，请稍后重试");
        }
    }
    
    /**
     * 用户取消报名
     */
    @PostMapping("/cancel/{id}")
    public Result<Void> cancelSignup(
            @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        activityService.cancelSignup(id, userId);
        return Result.success();
    }
    
    /**
     * 获取活动统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getActivityStats() {
        Map<String, Object> stats = activityService.getActivityStats();
        return Result.success(stats);
    }
    
    /**
     * 获取用户参与的活动列表
     */
    @GetMapping("/my")
    public Result<Page<Activity>> getMyActivities(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        Page<Activity> page = activityService.getMyActivities(pageNum, pageSize, userId);
        return Result.success(page);
    }
} 